//
//  AudioTransferTool.m
//  FuncFanc
//
//  Created by careate-hubing on 2021/6/28.
//  Copyright © 2021 huhu. All rights reserved.
//

#import "AudioTransferTool.h"
#import <Speech/Speech.h>

typedef void(^completedBlock)(NSString *result);



@interface AudioTransferTool ()<SFSpeechRecognitionTaskDelegate>

@property (nonatomic, strong) SFSpeechRecognizer *speechRecognizer;

@property (nonatomic, strong) AVAudioEngine *audioEngine;

@property (nonatomic, strong) SFSpeechAudioBufferRecognitionRequest *recognitionRequest;

@property (nonatomic, copy) completedBlock block;

@end

@implementation AudioTransferTool

+ (instancetype)sharedTool
{
    static AudioTransferTool *_sharedTool = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedTool = [[super allocWithZone:NULL]init];
        [SFSpeechRecognizer requestAuthorization:^(SFSpeechRecognizerAuthorizationStatus status) {
//            NSLog(@"status %@", status == SFSpeechRecognizerAuthorizationStatusAuthorized ? @"授权成功" : @"授权失败");
        }];
    });
    return _sharedTool;
}

+(instancetype)allocWithZone:(struct _NSZone *)zone{
    return [AudioTransferTool sharedTool];
}

+(instancetype)copyWithZone:(nullable NSZone *)zone{
    return [AudioTransferTool sharedTool];
}

-(id)mutableCopyWithZone:(nullable NSZone *)zone
{
    return [AudioTransferTool sharedTool];
}

-(void)initSpeechEngine
{
    if (!self.speechRecognizer) {
        NSLocale *locale = [NSLocale localeWithLocaleIdentifier:@"zh-CN"];
        self.speechRecognizer = [[SFSpeechRecognizer alloc]initWithLocale:locale];
    }
    if (!self.audioEngine) {
        self.audioEngine = [[AVAudioEngine alloc]init];
    }
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryRecord mode:AVAudioSessionModeMeasurement options:AVAudioSessionCategoryOptionDuckOthers error:nil];
    [audioSession setActive:YES withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:nil];
    if (self.recognitionRequest) {
        [self.recognitionRequest endAudio];
        self.recognitionRequest = nil;
    }
    self.recognitionRequest = [[SFSpeechAudioBufferRecognitionRequest alloc]init];
    self.recognitionRequest.shouldReportPartialResults = YES;
        
//    [self.speechRecognizer recognitionTaskWithRequest:self.recognitionRequest resultHandler:^(SFSpeechRecognitionResult * _Nullable result, NSError * _Nullable error) {
//        NSLog(@"is final: %d  result: %@", result.isFinal, result.bestTranscription.formattedString);
//        // 先把文字存储在tempstr 中，显示在 tv中。
//        if (result.isFinal) {
//            //  用最终文字替换刚才的临时文字。
////            self.tv.text = [NSString stringWithFormat:@"%@%@",self.tv.text,result.bestTranscription.formattedString];
//        }
//    }];
    
    [self.speechRecognizer recognitionTaskWithRequest:self.recognitionRequest delegate:self];
}

- (void)speechRecognitionTask:(SFSpeechRecognitionTask *)task didFinishRecognition:(SFSpeechRecognitionResult *)recognitionResult
{
    DebugLog(@"转化结果：%@",recognitionResult.bestTranscription.formattedString);
    if (_block) {
        _block(recognitionResult.bestTranscription.formattedString);
    }
}

- (void)speechRecognitionTaskWasCancelled:(SFSpeechRecognitionTask *)task
{
    DebugLog(@"取消");
}

-(void)startVoiceRecigizer
{
    DebugLog(@"开始语音转文字。");
    [self initSpeechEngine];
    AVAudioFormat *recordingFormat = [[self.audioEngine inputNode]outputFormatForBus:0];
    [[self.audioEngine inputNode]removeTapOnBus:0];
    [[self.audioEngine inputNode]installTapOnBus:0 bufferSize:1024 format:recordingFormat block:^(AVAudioPCMBuffer * _Nonnull buffer, AVAudioTime * _Nonnull when) {
        [self.recognitionRequest appendAudioPCMBuffer:buffer];
    }];
    [self.audioEngine prepare];
    [self.audioEngine startAndReturnError:nil];
}

-(void)stopVoiceRecigizerCompleteBlock:(void(^)(NSString *result))block
{
    DebugLog(@"stopVoiceRecigizer");
    _block = block;
    [[self.audioEngine inputNode]removeTapOnBus:0];
    [self.audioEngine stop];
    
    [self.recognitionRequest endAudio];
    self.recognitionRequest = nil;
}

@end
